
// 邮件详情管理模块
const EmailDetailsManager = {
    // 初始化详情模块
    init: function() {
        // 添加邮件详情加载遮罩层
        const detailContainer = $('#email-detail-container');
        if (detailContainer.length && !detailContainer.find('.local-loading-overlay').length) {
            detailContainer.append('<div class="local-loading-overlay" id="email-detail-loading"><div class="local-loading-spinner"></div></div>');
        }
    },

    // 查看邮件详情
    viewEmail: async function(accountId, emailId, element) {
        // 检查是否为草稿
        if (EmailModule.cache.currentFolder === 'Drafts') {
            try {
                // 草稿现在从专门的接口获取
                const draft = await Api.apiRequest(`/email-accounts/${accountId}/drafts/${emailId}`);
                EmailModule.openComposeModal({
                    title: '编辑草稿',
                    to: draft.recipients,
                    cc: draft.cc,
                    subject: draft.subject,
                    body: draft.body,
                    draftId: draft.id
                });
            } catch (error) {
                console.error('加载草稿失败:', error);
                layui.layer.msg('加载草稿失败');
            }
            return;
        }

        // 移动端/平板端：立即打开详情视图（与接口请求同步）
        if (typeof LayoutManager !== 'undefined' && (LayoutManager.state.isMobile || LayoutManager.state.isTablet)) {
            LayoutManager.openMobileDetail();
        }
        
        // 显示邮件详情加载遮罩层
        const detailContainer = $('#email-detail-container');
        let loadingOverlay = detailContainer.find('#email-detail-loading');
        
        // 如果遮罩层不存在，重新创建
        if (loadingOverlay.length === 0) {
            loadingOverlay = $('<div class="local-loading-overlay" id="email-detail-loading"><div class="local-loading-spinner"></div></div>');
            detailContainer.append(loadingOverlay);
        }
        
        loadingOverlay.addClass('active');

        // 立即添加选中状态，提供即时反馈
        const emailItem = $(`.email-item[data-email-id='${emailId}']`);
        if (emailItem.length) {
            // 移除之前选中的邮件的 'selected' 类
            $('.email-item.selected').removeClass('selected');
            // 为当前点击的邮件添加选中状态
            emailItem.addClass('selected');
        }

        try {
            // 并行获取邮件元数据和解析后的HTML内容
            const [email, emailContentResponse] = await Promise.all([
                Api.apiRequest(`/email-accounts/${accountId}/emails/${emailId}?folder=${EmailModule.cache.currentFolder}`),
                Api.apiRequest(`/email-accounts/${accountId}/emails/${emailId}/content?folder=${EmailModule.cache.currentFolder}`)
            ]);
            
            // 存储当前邮件
            EmailModule.cache.currentEmail = email;
            EmailModule.cache.currentEmail.html_content = emailContentResponse.content;
            EmailModule.cache.currentEmail.attachments = emailContentResponse.attachments || [];

            // 渲染邮件详情
            this.renderEmailDetail(email, emailContentResponse.content, emailContentResponse.attachments);

            // 确保邮件状态更新（移除未读状态）
            if (emailItem.length) {
                emailItem.removeClass('unread');
            }

        } catch (error) {
            console.error('加载邮件详情失败:', error);
            layui.layer.msg('加载邮件详情失败');
            
            // 如果加载失败，移除选中状态
            if (emailItem.length) {
                emailItem.removeClass('selected');
            }
        } finally {
            // 隐藏邮件详情加载遮罩层
            $('#email-detail-loading').removeClass('active');
        }
    },

    // 渲染邮件详情
    renderEmailDetail: function(email, htmlContent, attachments = []) {
        const container = $('#email-detail-container');
        if (!container.length) {
            console.error("错误: 未找到ID为 'email-detail-container' 的元素。");
            return;
        }

        // 使用统一的设备检测
        const isMobile = DeviceDetector.isMobile();

        // 保存遮罩层元素（如果存在的话）
        let loadingOverlay = container.find('.local-loading-overlay').detach();

        const to = email.to ? formatSender(email.to) : '无';
        const cc = email.cc ? escapeHtml(email.cc) : '无';
        const sender = email.sender ? formatSender(email.sender) : '无';

        // 获取文件类型和对应的图标
        const getFileTypeAndIcon = (filename) => {
            if (!filename) return { type: 'file-other', icon: 'layui-icon-file' };
            
            const ext = filename.split('.').pop().toLowerCase();
            
            // 图片文件
            const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'tif'];
            if (imageExts.includes(ext)) {
                return { type: 'file-image', icon: 'layui-icon-picture' };
            }
            
            // 文档文件
            const docExts = ['pdf', 'doc', 'docx', 'txt', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'rtf', 'csv'];
            if (docExts.includes(ext)) {
                return { type: 'file-document', icon: 'layui-icon-file' };
            }
            
            // 压缩文件
            const archiveExts = ['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'tgz'];
            if (archiveExts.includes(ext)) {
                return { type: 'file-archive', icon: 'layui-icon-layer' };
            }
            
            // 其他文件
            return { type: 'file-other', icon: 'layui-icon-file' };
        };

        // 生成附件HTML - 添加token到下载URL
        let attachmentsHtml = '';
        if (attachments && attachments.length > 0) {
            const token = localStorage.getItem('token');
            attachmentsHtml = `
                <div class="email-attachments">
                    <div class="attachments-title"><i class="layui-icon layui-icon-file"></i> 附件 (${attachments.length})</div>
                    <div class="attachments-list">
                        ${attachments.map(att => {
                            const { type, icon } = getFileTypeAndIcon(att.filename);
                            return `
                                <div class="attachment-item ${type}" 
                                     data-filename="${escapeHtml(att.filename)}"
                                     data-url="${Api.config.apiBaseUrl}/email-accounts/${email.email_account_id}/emails/${email.id}/attachments/${att.index}"
                                     onclick="EmailDetailsManager.downloadAttachment(this, '${escapeHtml(att.filename)}')">
                                    <i class="layui-icon ${icon}"></i>
                                    <div class="attachment-info">
                                        <div class="attachment-name">${escapeHtml(att.filename)}</div>
                                        <div class="attachment-size">${formatFileSize(att.size)}</div>
                                    </div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        }

        // 渲染邮件元信息
        const isSpecialFolder = ['Drafts', 'Sent'].includes(EmailModule.cache.currentFolder);

        // 根据是否为移动端决定初始的展开/折叠状态
        const initialClass = isMobile ? '' : 'expanded';

        container.html(`
            <div class="email-detail">
                <div class="email-info-panel ${initialClass}">
                    <div class="email-subject" onclick="this.parentElement.classList.toggle('expanded'); this.parentElement.classList.toggle('collapsed');">${escapeHtml(email.subject)}</div>
                    <div class="info-content">
                        <div class="info-grid">
                            <div class="info-label">发件人:</div><div class="info-value">${sender}</div>
                            <div class="info-label">收件人:</div><div class="info-value">${to}</div>
                            <div class="info-label">时间:</div><div class="info-value">${new Date(email.received_date).toLocaleString()}</div>
                            <div class="info-label">抄送:</div><div class="info-value">${cc}</div>
                        </div>
                        ${attachmentsHtml}
                    </div>
                    <div class="email-actions">
                        <div class="layui-btn-group">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="EmailDetailsManager.replyEmail(${email.id})"><i class="layui-icon layui-icon-reply-fill"></i><span class="button-text"> 回复</span></button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="EmailDetailsManager.forwardEmail(${email.id})"><i class="layui-icon layui-icon-next"></i><span class="button-text"> 转发</span></button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="EmailDetailsManager.markAsUnread(${email.email_account_id}, ${email.id})" style="display: ${isSpecialFolder ? 'none' : 'inline-block'};"><i class="layui-icon layui-icon-email"></i><span class="button-text"> 标记为未读</span></button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="translate-btn" onclick="EmailDetailsManager.translateEmail(${email.email_account_id}, ${email.id})"><i class="custom-icon-translate">中</i><span class="button-text"> 全文翻译</span></button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="retranslate-btn" onclick="EmailDetailsManager.translateEmail(${email.email_account_id}, ${email.id}, true)"><i class="layui-icon layui-icon-refresh"></i><span class="button-text"> 重新翻译</span></button>
                        </div>
                        <div class="layui-btn-group">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="EmailDetailsManager.deleteEmail(${email.email_account_id}, ${email.id})" style="display: ${isSpecialFolder ? 'none' : 'inline-block'};"><i class="layui-icon layui-icon-delete"></i><span class="button-text"> 删除</span></button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="EmailDetailsManager.permanentDeleteEmail(${email.email_account_id}, ${email.id})"><i class="layui-icon layui-icon-close-fill"></i><span class="button-text"> 彻底删除</span></button>
                        </div>
                    </div>
                </div>
                <div class="email-body-container">
                    <iframe id="email-content-iframe" frameborder="0" style="width: 100%; height: 100%;"></iframe>
                </div>
            </div>
        `);

        // 将邮件内容写入 iframe - 同时设置内容和拦截器
        const iframe = $('#email-content-iframe');
        if (iframe.length) {
            // 立即设置内容,不延迟
            iframe.prop('srcdoc', htmlContent);
            
            // 立即设置拦截器（load事件会在内容加载完成后触发）
            if (typeof LinkSafetyManager !== 'undefined') {
                LinkSafetyManager.interceptIframeLinks(iframe);
            } else {
                console.warn('LinkSafetyManager未加载，链接拦截功能不可用');
            }
        }

        // 重新添加遮罩层，如果不存在则创建
        if (loadingOverlay.length) {
            container.append(loadingOverlay);
        } else {
            loadingOverlay = $('<div class="local-loading-overlay" id="email-detail-loading"><div class="local-loading-spinner"></div></div>');
            container.append(loadingOverlay);
        }
    },

    // 回复邮件
    replyEmail: function() {
        if (!EmailModule.cache.currentEmail) {
            layui.layer.msg('请先选择一封邮件');
            return;
        }

        formatSenderStr = formatSender(EmailModule.cache.currentEmail.sender);
        const body = `<br><br><hr>--- 原始邮件 ---<br>发件人: ${formatSenderStr}<br>时间: ${new Date(EmailModule.cache.currentEmail.received_date).toLocaleString()}<br>主题: ${EmailModule.cache.currentEmail.subject}<br><br>${EmailModule.cache.currentEmail.html_content}`;

        // 使用senderToEmail函数提取发件人的邮箱地址
        const senderEmails = senderToEmail(EmailModule.cache.currentEmail.sender);
        const replyTo = senderEmails.length > 0 ? senderEmails.join(', ') : EmailModule.cache.currentEmail.sender;

        EmailModule.openComposeModal({
            title: '回复邮件',
            to: replyTo,
            cc: '',
            subject: 'Re: ' + EmailModule.cache.currentEmail.subject,
            body: body
        });
    },

    // 转发邮件
    forwardEmail: function() {
        if (!EmailModule.cache.currentEmail) {
            layui.layer.msg('请先选择一封邮件');
            return;
        }

        formatSenderStr = formatSender(EmailModule.cache.currentEmail.sender);
        const body = `<br><br><hr>--- 转发邮件 ---<br>发件人: ${formatSenderStr}<br>时间: ${new Date(EmailModule.cache.currentEmail.received_date).toLocaleString()}<br>主题: ${EmailModule.cache.currentEmail.subject}<br><br>${EmailModule.cache.currentEmail.html_content}`;

        EmailModule.openComposeModal({
            title: '转发邮件',
            subject: 'Fwd: ' + EmailModule.cache.currentEmail.subject,
            body: body
        });
    },

    // 删除邮件 - 复用统一方法
    deleteEmail: function(accountId, emailId) {
        EmailOperationsManager.deleteEmail(accountId, emailId);
    },

    // 标记为未读 - 复用统一方法
    markAsUnread: function(accountId, emailId) {
        EmailOperationsManager.markAsUnread(accountId, emailId);
    },

    // 彻底删除邮件 - 复用统一方法
    permanentDeleteEmail: function(accountId, emailId) {
        EmailOperationsManager.permanentDeleteEmail(accountId, emailId);
    },

    // 下载附件
    downloadAttachment: async function(element, filename) {
        const url = $(element).data('url');
        const token = localStorage.getItem('token');
        
        if (!url || !token) {
            layui.layer.msg('下载失败：缺少必要参数');
            return;
        }

        try {
            // 使用fetch API下载文件，携带token
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                throw new Error('下载失败');
            }

            // 获取blob数据
            const blob = await response.blob();
            
            // 创建下载链接
            const downloadUrl = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = downloadUrl;
            a.download = filename;
            
            // 触发下载
            document.body.appendChild(a);
            a.click();
            
            // 清理
            window.URL.revokeObjectURL(downloadUrl);
            document.body.removeChild(a);
            
        } catch (error) {
            console.error('下载附件失败:', error);
            layui.layer.msg('下载附件失败');
        }
    },

    // 全文翻译邮件
    translateEmail: async function(accountId, emailId, forceTranslate = false) {
        const translateBtn = $('#translate-btn');
        const retranslateBtn = $('#retranslate-btn');
        const iframe = $('#email-content-iframe');
        // 精确定位到邮件详情面板中的标题，避免影响邮件列表中的标题
        const subjectDiv = $('#email-detail-container .email-subject');
        
        if (!iframe.length) {
            layui.layer.msg('邮件内容未加载');
            return;
        }

        // 检查是否为重新翻译模式
        if (forceTranslate) {
            // 跳过原文/译文切换逻辑，直接重新翻译
        } else if (translateBtn.data('translated')) {
            // 切换回原文（从缓存的原文中恢复）
            const originalContent = translateBtn.data('originalContent');
            const originalSubject = translateBtn.data('originalSubject');
            if (originalContent) {
                iframe.prop('srcdoc', originalContent);
                if (originalSubject && subjectDiv.length) {
                    subjectDiv.text(originalSubject);
                }
                translateBtn.html('<i class="custom-icon-translate">中</i><span class="button-text"> 全文翻译</span>');
                translateBtn.data('translated', false);
                translateBtn.removeData('originalContent');
                translateBtn.removeData('originalSubject');
            }
            return;
        }

        // 缓存原文内容和标题，用于切换回原文
        const originalContent = EmailModule.cache.currentEmail.html_content;
        const originalSubject = EmailModule.cache.currentEmail.subject;
        translateBtn.data('originalContent', originalContent);
        translateBtn.data('originalSubject', originalSubject);

        // 禁用按钮并显示加载状态
        translateBtn.prop('disabled', true);
        retranslateBtn.prop('disabled', true);
        const originalTranslateHtml = translateBtn.html();
        translateBtn.html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><span class="button-text"> 翻译中...</span>');

        try {
            // 传递force_translate参数到后端
            const response = await Api.apiRequest(
                `/email-accounts/${accountId}/emails/${emailId}/translate?force_translate=${forceTranslate}`,
                { method: 'POST' }
            );

            if (response && response.content) {
                // 显示翻译后的内容
                iframe.prop('srcdoc', response.content);
                
                // 更新标题（如果有翻译后的标题）
                if (response.title && subjectDiv.length) {
                    subjectDiv.text(response.title);
                }
                
                // 更新按钮状态
                translateBtn.html('<i class="custom-icon-translate">英</i><span class="button-text"> 显示原文</span>');
                translateBtn.data('translated', true);
            } else {
                throw new Error('翻译结果为空');
            }
        } catch (error) {
            console.error('翻译失败:', error);
            
            // 显示具体的错误信息
            let errorMsg = '翻译失败';
            if (error && error.message) {
                errorMsg = error.message;
            } else if (typeof error === 'string') {
                errorMsg = error;
            }
            
            layui.layer.msg(errorMsg, { time: 5000 }); // 延长显示时间到5秒
            
            // 恢复按钮状态
            translateBtn.html(originalTranslateHtml);
        } finally {
            translateBtn.prop('disabled', false);
            retranslateBtn.prop('disabled', false);
        }
    }
};